from flask import request, jsonify, current_app
from flask_login import login_required
import flask_excel as excel
from ..base import base
import requests
import time
import pandas as pd
import json
from copy import deepcopy

@base.route('/ysmxUpload', methods=['POST'])
@login_required
def analyze_excel():
    # 内置配置参数
    ####################################################
    AI_AGENT_CREATE = "http://20.1.57.46:21180/lmp-cloud-ias-server/api/session/create"
    AI_AGENT_RUN = "http://20.1.57.46:21180/lmp-cloud-ias-server/api/session/run"
    AI_AGENT_DELETE= "http://20.1.57.46:21180/lmp-cloud-ias-server/api/session/delete"
    HEADERS_METADATA = {
        'Content-Type': 'application/json',
        'Authorization':'12d84378abda42fc93f9ac44291cc107',
        'Accept': '*/*',
        'User-Agent': 'PostmanRuntime/7.29.0'
    }
    # MAX_FILE_SIZE = 50 * 1024 * 1024  # 5MB限制（单位：字节）
    REQUEST_TIMEOUT = 10  # 接口调用超时时间（秒）
    # REQUEST_INTERVAL = 0.1  # 请求间隔（秒）
    REQUIRED_COLUMNS = {'元素中文名', '元素英文名', '说明'}
    ####################################################

    # 文件校验
    if 'file' not in request.files:
        return jsonify({"code": 400, "msg": "未上传文件"}),400

    file = request.files['file']
    if not file.filename.lower().endswith(('.xls', '.xlsx')):
        return jsonify({"code": 400, "msg": "仅支持.xls/.xlsx文件"}),400

    try:
        # 解析Excel
        data = pd.read_excel(file).fillna('')
        # 数据结构校验
        if data.empty or not REQUIRED_COLUMNS.issubset(data.columns):
            return jsonify({"code": 400, "msg":"Excel列头缺失，必须包含：元素中文名、元素英文名、说明"}),400

        results = []

        # 调用智能体返回session
        session_id = None
        response_session = requests.post(
            AI_AGENT_CREATE,
            json={
                "agentId":"a24fc651-9427-4d13-b462-32cd4dbc86b9",
	            "agentVersion":"1747103217940"
            },
            headers=HEADERS_METADATA
        )

        if response_session.status_code != 200:
            print(f"会话创建失败[HTTP {response_session.status_code}]: {response_session.text}")
            return jsonify({
                "code": 503,
                "msg": f"智能体服务不可用（HTTP {response_session.status_code}）"
            }), 503

        response_session_data = response_session.json()

        if  response_session_data.get('code') != '000000':
            # current_app.logger.error(f"会话创建失败: {response_session_data.message}")
            print(f"会话创建失败: {response_session_data.get('message')}")
            return jsonify({"code": 500, "msg": "智能体初始化失败"}),500

        session_id = response_session_data['data']['sessionId']

        # 处理每条记录
        for idx, (_, row) in enumerate(data.iterrows(), 1):
            record_start = time.time()
            item = row.to_dict()
            print(f"正在处理第 {idx} 条记录:  {item}")
            try:
                # 构建请求数据
                payload = {
                    "agentId": "a24fc651-9427-4d13-b462-32cd4dbc86b9",
                    "agentVersion": "1747103217940",
                    "sessionId": session_id,
                    "stream": "false"
                }
                text_data = {
                    'ele_ch': str(item.get('元素中文名', '')).strip(),
                    'ele_en': str(item.get('元素英文名', '')).strip(),
                    'explain': str(item.get('说明', '')).strip()
                }
                # 确保 text_data 的值为标准 JSON 格式
                # payload["text"] = json.dumps(text_data, ensure_ascii=False)  # 确保中文字符正确编码
                payload["text"] = f'{{"ele_ch":"{text_data["ele_ch"]}","ele_en":"{text_data["ele_en"]}","explain":"{text_data["explain"]}"}}'
                # 调用智能体接口
                response_conversation = requests.post(
                    AI_AGENT_RUN,
                    json=payload,
                    headers=HEADERS_METADATA,
                    timeout=REQUEST_TIMEOUT
                )

                # 处理响应
                processed_result ={}
                if response_conversation.status_code != 200:
                    print(f"会话响应失败[HTTP {response_conversation.status_code}]: {response_conversation.text}")
                    return jsonify({
                        "code": 503,
                        "msg": f"智能体服务不可用（HTTP {response_conversation.status_code}）"
                    }), 503

                response_conversation_data = response_conversation.json()
                if response_conversation_data.get('code') == '000000':
                    result_data = json.loads(response_conversation_data.get('data').get('answer'))
                    processed_result = {
                        "输入元素中文名": item.get('元素中文名', ''),
                        "输入元素英文名": item.get('元素英文名', ''),
                        "输入说明": item.get('说明', ''),
                        "审核结果": result_data.get('审核结果', '未知状态'),
                        "相似记录条数": result_data.get('相似记录条数', ''),
                        "相似记录": result_data.get('相似记录', [])
                    }
                else:
                    processed_result = {
                        "输入元素中文名": item.get('元素中文名', ''),
                        "输入元素英文名": item.get('元素英文名', ''),
                        "输入说明": item.get('说明', ''),
                        "审核结果": f"接口错误({response_conversation_data.get('code')})",
                        "相似记录条数": 0,
                        "相似记录": []
                    }

                results.append(processed_result)

            except requests.exceptions.Timeout:
                base_payload = deepcopy(payload) if payload else {}
                results.append({
                    **base_payload,
                    "审核结果": "请求超时",
                    "相似记录条数": 0,
                    "相似记录": []
                })
            except json.JSONDecodeError as e:
                base_payload = deepcopy(payload) if payload else {}
                results.append({
                    **base_payload,
                    "审核结果": f"Json 解析错误: {str(e)}",
                    "相似记录条数": 0,
                    "相似记录": []
                })
            except Exception as e:
                base_payload = deepcopy(payload) if payload else {}
                results.append({
                    **base_payload,
                    "审核结果": f"处理异常: {str(e)}",
                    "相似记录条数": 0,
                    "相似记录": []
                })

        return jsonify({
            "code": 200,
            "msg": f'成功处理{len(results)}条记录',
            "data": results
        }),200

    except Exception as e:
        current_app.logger.error(f"系统异常: {str(e)}")
        return jsonify({
            "code": 500,
            "msg": f'服务器内部错误: {str(e)}'
        }),500
    finally:
        try:
            if session_id:
                # 调用智能体关闭接口
                requests.post(
                    AI_AGENT_DELETE,
                    json={
                        "agentId":"a24fc651-9427-4d13-b462-32cd4dbc86b9",
	                    "agentVersion":"1747103217940",
                        "sessionId":session_id
                    },
                    headers=HEADERS_METADATA
                    )
                session_id = None
                current_app.logger.info("智能体会话已关闭")
                print("智能体会话已关闭")
        except Exception as e:
            current_app.logger.error(f"关闭会话时发生异常: {str(e)}")

